#include "dialog.h"
#include "ui_dialog.h"
#include <QMessageBox>
#include <QDebug>

//sudo apt-get install libgl1-mesa-dev
//sudo apt-get install fcitx-frontend-qt5

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    status = false;
    serverAddr = new QHostAddress();
    ui->sendButton->setEnabled(false);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_sendButton_clicked()
{
    if (ui->lineEdit->text().isEmpty())
    {
        return;
    }

    int length = 0;
    QString msg = username + ": " + ui->lineEdit->text();

    if ((length = tcpSocket->write(msg.toUtf8(), msg.size())) != msg.size())
    {
        return;
    }

    ui->lineEdit->clear();
}

void Dialog::on_enterChatRoomButton_clicked()
{
    if (!status)
    {
        if (ui->username->text().isEmpty())
        {
            QMessageBox::information(this, tr("error"), tr("username error!"));
            return;
        }

        username = ui->username->text();

        QString ip = ui->serverAddr->text();
        if (!serverAddr->setAddress(ip))
        {
            QMessageBox::information(this, tr("error"), tr("server ip address error!"));
            return;
        }

        int port = ui->serverPort->text().toInt();

        tcpSocket = new QTcpSocket(this);
        connect(tcpSocket, SIGNAL(connected()), this, SLOT(onConnected()));
        connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
        connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(onDataRecved())); // slot名字填错编译不会报错，运行也不会报错，我擦。。。

        tcpSocket->connectToHost(*serverAddr, port);
        status = true;
    }
    else
    {
        int length = 0;
        QString msg = username + tr(": Leave chat room");

        if ((length = tcpSocket->write(msg.toUtf8(), msg.size())) != msg.size())
        {
            return;
        }

        tcpSocket->disconnectFromHost();
        status = false;
    }
}

void Dialog::onConnected()
{
    ui->sendButton->setEnabled(true);
    ui->enterChatRoomButton->setText(tr("退出"));

    int length = 0;
    QString msg = username + tr(": Enter chat room");

    if ((length = tcpSocket->write(msg.toLatin1(), msg.length())) != msg.length())
    {
        return;
    }
}

void Dialog::onDisconnected()
{
    ui->sendButton->setEnabled(false);
    ui->enterChatRoomButton->setText(tr("进入聊天室"));
}

void Dialog::onDataRecved()
{
    qDebug() << "on data recved";

    while (tcpSocket->bytesAvailable() > 0)
    {
        QByteArray data;
        data.resize(tcpSocket->bytesAvailable());

        tcpSocket->read(data.data(), data.size());
        QString msg = data.data();
        ui->listWidget->addItem(msg.left(msg.size()));
    }
}
